import { YFnObj, YFnParams, YItemConfig } from '../../interface';
function bindHandler(
  config: YItemConfig,
  mergeData: { [key: string]: any },
  handler?: (
    params: { [key: string]: any },
    mergeData: { [key: string]: any }
  ) => { [key: string]: any }
) {
  const value = config.bind || {};
  return (options: YFnParams) => {
    const result = typeof value === 'function' ? value(options) : value;
    return handler ? handler(result, mergeData) : { ...result, ...mergeData };
  };
}

const interception: {
  itemConfig?: { [key: string]: (config: YItemConfig) => YItemConfig };
  validate?: (form: any, callback: (isValid: boolean) => void) => void;
  event?: Function;
  get?: (vm: any, prop: string, value: any, config: any) => any;
  set?: (vm: any, prop: string, value: any, config: any) => any;
  props?: (props: { [key: string]: any }, vm: any) => { [key: string]: any };
  rule?: (rule: any, form: any) => any;
} = {
  itemConfig: {
    '*'(config) {
      return config;
    },
    button(config) {
      config.bind = bindHandler(config, {}, (params, mergeData) => {
        if (
          params.type &&
          !['submit', 'reset', 'button'].includes(params.type)
        ) {
          params.theme = params.theme || params.type;
          delete params.type;
        }
        return params;
      });
      return config;
    },
    radioGroup(config) {
      config.optionHandler = (options: { [key: string]: any }[]) =>
        options.map((option) => {
          return {
            type: config.optionType || 'radio',
            nodes: option.label,
            bind: option,
          };
        });
      return config;
    },
    image(config) {
      config.type = 'img';
      return config;
    },
    date(config) {
      config.bind = bindHandler(config, { mode: 'date' });
      return config;
    },
    dateTime(config) {
      config.bind = bindHandler(config, {
        mode: 'date',
        enableTimePicker: true,
      });
      return config;
    },
    mouth(config) {
      config.bind = bindHandler(config, { mode: 'mouth' });
      return config;
    },
    year(config) {
      config.bind = bindHandler(config, { mode: 'year' });
      return config;
    },
    monthRange(config) {
      config.bind = bindHandler(config, { mode: 'year' });
      return config;
    },
    yearRange(config) {
      config.bind = bindHandler(config, { mode: 'year' });
      return config;
    },
    dateTimeRange(config) {
      config.bind = bindHandler(config, {
        mode: 'date',
        enableTimePicker: true,
      });
      return config;
    },
  },
  validate(form: any, callback: (isValid: boolean) => void) {
    form.validate().then((result: any) => {
      callback(result === true);
    });
  },
  props(props) {
    if (!('labelAlign' in props) && 'labelPosition' in props) {
      props.labelAlign = props.labelPosition;
    }
    return props;
  },
};

export default interception;
